﻿using System;
using System.Collections.Generic;
using System.Linq;
using CoreHelper.Reflection;
using CoreHelper.Validation.Validators;

namespace CoreHelper.Validation
{
    public sealed class ValidationContext
    {
        List<ValidationItem> _validationList;
        public ValidationContext(object instance)
        {
            _validationList = new List<ValidationItem>();
            var typeInfo = TypeCachedManager.GetTypeCachedInfo(instance.GetType());
            foreach (var kv in typeInfo.PropInvokerDict)
            {
                var attrs = kv.Value.Property.GetCustomAttributes(false);
                var item = new ValidationItem { Name = kv.Key, Value = kv.Value.Get(instance), Validations = new List<BaseValidatorAttribute>() };
                _validationList.Add(item);
                foreach (var attr in attrs)
                {
                    var validation = attr as BaseValidatorAttribute;
                    if (validation != null)
                    {
                        item.Validations.Add(validation);
                    }
                }
                item.Validations = item.Validations.OrderBy(x => x.Sort).ToList();
            }
        }
        public ValidationContext(List<ValidationItem> validationList)
        {
            _validationList = validationList;
        }
        public ValidationItem GetValidationItem(string name)
        {
            return _validationList.FirstOrDefault(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
        }
        internal List<ValidationItem> ValidationList
        {
            get
            {
                return _validationList;
            }
        }
    }
}
